package cn.aifeix.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义过滤器
 */
@Component
public class LoginFilter extends ZuulFilter {

    /**
     * filter类型，可以通过父类查看返回值信息示列
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * filter执行顺序，数字越小，执行时机越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * true 执行run false 不执行run
     * @return
     */
    @Override
    public boolean shouldFilter() {
        // 获取请求地址
        String requestURI = RequestContext.getCurrentContext().getRequest().getRequestURI();
        // 判断请求路径是否以login/register结尾，包含就不执行登录业务校验，所以返回false
        if (requestURI.endsWith("login") || requestURI.endsWith("register")){
            return false;
        }
        // 3.如果不包含那么说明用户访问的资源是受保护的资源，那么需要执行登录校验
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        String token = RequestContext.getCurrentContext().getRequest().getHeader("token");
        if (StringUtils.isEmpty(token)){
            try {
                HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                Map<String,Object> map = new HashMap<>();
                map.put("success", false);
                map.put("message", "请登录");
                map.put("resultObj", "noLogin");
                String resultJsonstr = JSONObject.toJSONString(map);
                writer.write(resultJsonstr);
                writer.close();
                // 切断后续filter执行
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
